import pickle
import base64
from django_redis import get_redis_connection


def merge_cart_to_redis(request, user, response):
    """合并购物车数据"""

    # 获取cookie中的数据
    cookie_cart = request.COOKIES.get('cart')
    if not cookie_cart:
        return response

    # 解码
    # 解析cookie购物车数据
    cookie_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))

    # 接受商品的数量和状态信息
    cart = {}
    # 记录redis勾选状态中应该增加的sku_id
    redis_cart_selected_add = []

    # 记录redis勾选状态中应该删除的sku_id
    redis_cart_selected_remove = []
    for sku_id, count_selected_dict in cookie_cart.items():
        '''
        [(key, value), (key, value)]

        count_selected_dict
        {'count': 10, 'selected':true}
        '''
        # 处理商品数量
        cart[sku_id] = count_selected_dict['count']
        # 状态
        if count_selected_dict['selected']:
            redis_cart_selected_add.append(count_selected_dict['selected'])
        else:
            redis_cart_selected_remove.append(count_selected_dict['selected'])

    if cart:
        # 合并到redis中
        conn = get_redis_connection('cart')
        pl = conn.pipeline()
        pl.hmset('cart_%s' % user.id, cart)
        if redis_cart_selected_add:
            pl.sadd('cart_selected_%s' % user.id, *redis_cart_selected_add)
        if redis_cart_selected_remove:
            pl.srem('cart_selected_%s' % user.id, *redis_cart_selected_remove)
        pl.execute()

    # 删除cookie中的所有购物车信息
    response.delete_cookie('cart')
    # 返回
    return response
